package gui.components;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

import controller.DrawingController;
import data.DrawingSettings;
/**
 * A WhiteboardCanvas represents a canvas which is used to draw the shapes on
 * @author Jie Zhao(288654)
 *
 */
public class WhiteboardCanvas extends JPanel {
	private DrawingController controller = null;
	private DrawingSettings drawingSettings = null;

	// private Image buffer = null;

	public WhiteboardCanvas() {
		controller = DrawingController.getInstance();
		drawingSettings = DrawingSettings.getInstance();

		setBackground(Color.WHITE);
		drawingSettings.setCanvasBackground(this.getBackground());

		setOpaque(true);
		setDoubleBuffered(true);
		this.addMouseListener(controller);
		this.addMouseMotionListener(controller);
		this.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
	}

	/**
	 * save the canvas to an image, supports JPEG and PNG file
	 * 
	 * @param file
	 * @param format
	 */
	public void saveToImage(File file) {
		try {
			File f = new File(file.getAbsolutePath().concat(".png"));
			if(!f.exists())
			{
				f.createNewFile();
			}
			Dimension size = getSize();
			BufferedImage image = new BufferedImage(size.width, size.height,
					BufferedImage.TYPE_INT_ARGB);
			Graphics2D g2d = image.createGraphics();
			controller.paint(g2d);
			g2d.dispose();
			ImageIO.write(image, "png", f);
		} catch (Exception e) {
		}
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		controller.paint(g);
	}

}
